package com.system.boss.optlog.service;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.system.boss.optlog.dto.IPAddr;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class IpComponent {

	@Resource
	private RestTemplate restTemplate;
	@Resource
	private RedisTemplate<String, IPAddr> redisTemplate;
	private final String REIDSIPADDRKEY="system::ipaddr";
	
	public String getIpLocation(String ipaddr) {
		String result = null;
		if(ipaddr == null || ipaddr == "")
			return null;
		var setOps = redisTemplate.opsForSet();
		var set = setOps.members(REIDSIPADDRKEY);
		var queryip = IPAddr.builder().origip(ipaddr).build();
		if(set.contains(queryip)) {
			for(IPAddr dest:set) {
				if(dest.equals(queryip)) {
					return dest.getLocation();
				}
			}
		}
		try {
			ResponseEntity<String> entity = restTemplate.getForEntity("https://opendata.baidu.com/api.php?query="+ipaddr+"&resource_id=6006&oe=utf8", String.class);
			result = entity.getBody();
		} catch (Exception e) {
			return null;
		}
		if(result != null) {
			JSONObject obj = JSONObject.parseObject(result);
			String status = obj.getString("status");
			if(status != null && status.equals("0")) {
				JSONArray datas = obj.getJSONArray("data");
				if(datas.size()==0) {
					return null;
				} else {
					JSONObject data = datas.getJSONObject(0);
					String originQuery = data.getString("OriginQuery");
					String location = data.getString("location");
					queryip.setLocation(location);
					setOps.add(REIDSIPADDRKEY, queryip);
					log.debug("[IP查询]查询地址：{}，查询结果：{}",originQuery,location);
					return location;
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}
}
